<template>
  <div style="flex: 1;">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item>
        <el-table :data="props.modelValue" border style="width: 100%">
          <el-table-column label="序号" width="60" align="center">
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="参数名称" prop="paramName" >
            <template #default="{ row }">
              <el-input v-model="row.paramName" placeholder="请输入参数名称" />
            </template>
          </el-table-column>
          <el-table-column label="参数类型" prop="paramType" >
            <template #default="{ row }">
              <el-select
                v-model="row.paramType"
                placeholder="请选择参数类型"
                @change="subtaskForm()"
                style="width: 100%"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- <el-table-column label="参数描述" prop="paramDes"  width="120">
          <template #default="{ row }">
            <el-input
              v-model="row.paramDes"
              type="textarea"
              :rows="1"
              placeholder="请输入参数描述"
            />
          </template>
        </el-table-column> -->

          <el-table-column label="输入值" prop="paramValue" width="300">
            <template #default="{ row }">
              <inputUpload
                :taskId="newScriptId"
                v-model:paramValue="row.paramValue"
                v-if="row.paramType == 'file'"
              ></inputUpload>
              <el-input
                v-else
                v-model="row.paramValue"
                placeholder="请输入值"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100" align="center">
            <template #default="{ $index, row }">
              <el-button
                type="primary"
                v-if="row.paramType == 'file'"
                size="small"
                @click="settingRow(row)"
                :icon="Setting"
                circle
              />
              <!-- <el-button
              type="danger"
              size="small"
              @click="deleteRow(httpReq, $index)"
              :icon="Delete"
              circle
            /> -->
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-button style="width: 100%" @click="addNewRow(httpReq)" class="mt-4">
        <el-icon><plus /></el-icon>添加行
      </el-button> -->
      </el-form-item>
    </el-form>
    <BaseDialog
      v-model="showTxtDialog"
      title="表单弹窗"
      :before-close="handleBeforeClose"
      @confirm="submitTxt"
    >
      <txtEdit
        v-if="showTxtDialog"
        ref="txtEditValue"
        :txtDoc="txtDoc"
      ></txtEdit>
    </BaseDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { gmtTaskinfosave, gmtTaskinfo } from "@/api/gmtTask";
import type { UploadInstance } from "element-plus";
import inputUpload from "./inputUpload.vue";
import { Plus, Delete, Setting } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import txtEdit from "../gmtScriptView/txtEdit.vue";

// saveDynamicForm 定义
interface saveDynamicForm {
  resId?: string;
  httpUrl?: string;
  httpMethod?: string;
  httpReq?: string | string[];
}

// taskForm 定义
interface taskForm {
  taskName?: string;
  taskDes?: string;
  taskContent?: string;
}

// Props 定义
interface Props {
  modelValue?: any;
  disabled?: boolean;
  newScriptId: any;
  id?: string;
  plugins?: string | string[];
  toolbar?: string | string[];
  data?: any;
  taskForm?: taskForm;
  scriptValue: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: [
    {
      paramName: "",
      paramType: "",
      paramDes: "",
      paramValue: "",
    },
  ],
  newScriptId: "",
  disabled: false,
  id: "111",
  plugins: "advlist autolink lists link image table wordcount",
  toolbar:
    "undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media table | removeformat",
  data: {},
  scriptValue: "",
});

const newtaskId = ref();
const router = useRouter();
const route = useRoute();

//txt编辑弹窗
const showTxtDialog = ref(false);
const txtEditValue = ref();
const txtDoc = ref();

const newScriptId = ref(route.params.id);
const editorId = ref(props.id);
const formRef = ref(null);
const fristFillIn = ref(true);
const form: saveDynamicForm = reactive({});

const rules = reactive({
  httpUrl: [{ required: true, message: "请输入资源地址", trigger: "blur" }],
});

// 参数类型选项
const typeOptions = [
  { value: "1101", label: "字符串" },
  { value: "1102", label: "日期" },
  { value: "1103", label: "数字" },
  { value: "file", label: "文件" },
];

const methodOptions = [
  { value: "POST", label: "POST" },
  { value: "GET", label: "GET" },
];

// 资源请求参数（Json）
const httpReq = ref(
  props.modelValue
    ? props.modelValue
    : [
        {
          paramName: "",
          paramType: "",
          paramDes: "",
          paramValue: "",
        },
      ]
);

watch(props.modelValue, (newTheme) => {
  console.log("props.modelValue", props.modelValue);
  httpReq.value = props.modelValue;
});

// Emits 定义
const emit = defineEmits<{
  (e: "update:modelValue", value: any): void;
  (e: "update:newScriptId", value: any): void;
}>();

// 如果是编辑，加载用户数据
onMounted(() => {});

const uploadRef = ref<UploadInstance>();

const submitUpload = () => {
  uploadRef.value!.submit();
};

//表单提交
const subtaskForm = async () => {
  if (route.params.id == "add" && fristFillIn.value) {
    const data: any = await gmtTaskinfosave({
      taskName: props.taskForm.taskName,
      taskDes: props.taskForm.taskDes,
      scriptId: props.scriptValue,
    });
    newScriptId.value = data;
    fristFillIn.value = false;
  }
};

const settingRow = async (row) => {
  txtDoc.value = row;
  txtDoc.value.newScriptId = newScriptId.value;
  showTxtDialog.value = true;
};

// 添加新行
const addNewRow = (tableData) => {
  tableData.push({
    paramName: "",
    paramType: "",
    paramDes: "",
    paramValue: "",
  });
};

// 删除行
const deleteRow = (tableData, index) => {
  if (tableData.length > 1) {
    tableData.splice(index, 1);
  } else {
    ElMessage.warning("至少保留一行数据");
  }
};

//是否是新增
const isNatAdd = async () => {
  if (route.params.id == "add") {
    if (Object.keys(props.data).length === 0) {
      ElMessage.error("请先填写资源类型信息");
    } else {
      const data: any = await gmtTaskinfosave(props.data);
      editorId.value = data;
    }
  }
};

//取消txt编辑
const handleBeforeClose = () => {};

const submitTxt = async () => {
  // try {
  await txtEditValue.value.saveText();
  // } catch (error) {
  //   console.error("保存文本失败:", error);
  // } finally {
  showTxtDialog.value = false;
  // }
};

// 保存数据
const saveData = async () => {
  emit("update:modelValue", props.modelValue);
  emit("update:newScriptId", newScriptId.value);
};

defineExpose({
  saveData,
  isNatAdd,
});
</script>

<style scoped>
.user-edit-container {
  padding: 20px;
}

/* .editable-table-container {
  padding: 20px;
} */

.add-btn {
  margin-bottom: 15px;
}

.footer {
  margin-top: 15px;
  text-align: right;
}

.el-input,
.el-textarea {
  width: 100%;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 32px;
}
</style>
